package com.ruyuan2020.furnishing.trade.util;

import com.ruyuan2020.common.util.DateTimeUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;

@Component
public class TradeNoGenerator {

    /**
     * 订单号生成计数器
     */
    private static volatile long orderNumCount = 0L;

    public String generate() {
        String tradeNo;
        synchronized (TradeNoGenerator.class) {
            long nowLong = Long.parseLong(DateTimeUtils.formatDateTime(DateTimeUtils.currentDateTime(), "yyyyMMddHHmmssSSS"));
            long MAX_PER_SIZE = 1000L;
            if (orderNumCount > MAX_PER_SIZE) {
                orderNumCount = 0L;
            }
            String ip;
            try {
                InetAddress ip4 = Inet4Address.getLocalHost();
                ip = ip4.getHostAddress();
                ip = StringUtils.leftPad(ip.substring(ip.lastIndexOf(".") + 1), 3, '0') + RandomStringUtils.randomNumeric(3);
            } catch (UnknownHostException e) {
                ip = RandomStringUtils.randomNumeric(6);
            }
            //组装订单号
            String countStr = MAX_PER_SIZE + orderNumCount + "";
            tradeNo = nowLong + ip + countStr.substring(1);
            orderNumCount++;
        }
        return tradeNo;
    }
}
